﻿#include "SLT_thread_pool.h"


int slt_thread_pool::init(int _tNum)
{
    m_threadRun = true;
    for (int n = 0; n < _tNum; n++)
    {
        std::thread *pt = new std::thread(std::bind(&slt_thread_pool::thread_pool_cycle, this));
        m_threadList.push_back(pt);
    }


    return 0;
}

int slt_thread_pool::post_task(slt_thread_task* _ptask)
{
    std::unique_lock<std::mutex> lc(m_mutex);
    m_taskList.push_back(_ptask);
    m_cond.notify_one();
    return 0;
}
void slt_thread_pool::thread_pool_cycle()
{
    slt_thread_task* ptask = nullptr;
    while (m_threadRun) {
        {
            ptask = nullptr;
            std::unique_lock<std::mutex> lc(m_mutex);
            while (m_taskList.empty()) {
                m_cond.wait(lc);
            }
            ptask = m_taskList.front();
            m_taskList.pop_front();
        }
        
        ptask->onRun();
        ptask->destory();
    }
}